package com.net128.beatportapps.downloader;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class AppDialog {
	private int ROW_H = 25;
	private Box labelPanel = Box.createVerticalBox();
	private Box inputPanel = Box.createVerticalBox();
	private boolean firstInput=true;
	private static ImageIcon icon;
	
	protected static void setAppImageIcon(Image appImage) {
		icon = new ImageIcon(appImage.getScaledInstance(64, -1, Image.SCALE_SMOOTH));
	}
	
    protected int showOptionDialog(String title, int optionType, Object[] options, 
    		Object initialValue, final JComponent focusedComponent) throws HeadlessException {
		JPanel preferencesPanel = new JPanel(false);
		preferencesPanel.add(labelPanel, BorderLayout.WEST);
		preferencesPanel.add(inputPanel, BorderLayout.CENTER);
		JOptionPane pane = 
			new JOptionPane(preferencesPanel, JOptionPane.QUESTION_MESSAGE, optionType, icon, options, initialValue);
		pane.setInitialValue(initialValue);
		JDialog dialog = pane.createDialog(null, title);
		dialog.addComponentListener(new ComponentAdapter(){
			public void componentShown(ComponentEvent ce) {
				focusedComponent.requestFocus();				
			}
		});

		pane.selectInitialValue();
		dialog.setVisible(true);
		dialog.dispose();

		Object selectedValue = pane.getValue();

		if (selectedValue == null)
			return JOptionPane.CLOSED_OPTION;
		if (options == null) {
			if (selectedValue instanceof Integer)
				return ((Integer) selectedValue).intValue();
			return JOptionPane.CLOSED_OPTION;
		}
		for(int i=0; i<options.length; i++) {
			if (options[i].equals(selectedValue))
				return i;
		}
		return JOptionPane.CLOSED_OPTION;
	}

	protected void addInput(String label, Component component, int w) {
		int h = ROW_H;
		if (firstInput) {
			labelPanel.add(Box.createVerticalStrut(8));
		}
		JLabel labelComponent = new JLabel(label, JLabel.RIGHT);
		JPanel labelContainer = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
		labelContainer.add(labelComponent);
		labelContainer.setPreferredSize(new Dimension((int) (labelComponent
				.getPreferredSize().getWidth()), h));

		labelPanel.add(labelContainer);
		Component compPanel;
		if(w>0) {
			compPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
			component.setPreferredSize(new Dimension(w, h));
			compPanel.setPreferredSize(new Dimension(w, h));
			((JPanel)compPanel).add(component);
		} else {
			compPanel=component;
		}
		inputPanel.add(compPanel);
		firstInput = false;
	}
}
